package com.example.springboot.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.resp.Result;
import com.example.springboot.common.utils.JWTUtils;
import com.example.springboot.common.utils.JwtToken;
import com.example.springboot.user.entity.AdminEntity;
import com.example.springboot.user.mapper.AdminMapper;
import com.example.springboot.user.service.AdminService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpSession;
import lombok.Data;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Objects;

/**
 * <p>
 * 管理员表 前端控制器
 * </p>
 *
 * @author jiang
 * @since 2025-04-17
 */
@RestController
@RequestMapping("/adminEntity")
public class AdminController {

    private final AdminService service;
    private final AdminMapper mapper;

    public AdminController(AdminService service, AdminMapper mapper) {
        this.service = service;
        this.mapper = mapper;
    }

    @JwtToken
    @Operation(summary = "列表")
    @GetMapping("/adminList")
    public Result<?> adminList() {
        return Result.success(service.list());
    }

    @JwtToken
    @Operation(summary = "获取")
    @PostMapping("/adminId")
    public Result<?> adminId(@RequestParam Integer id) {
        return Result.success(mapper.selectById(id));
    }

    @JwtToken
    @Operation(summary = "列表分页")
    @PostMapping("/adminListPage")
    public Result<?> adminListPage(@RequestParam Integer page, @RequestParam Integer pageSize) {
        Page<AdminEntity> rowPage = new Page<>(page, pageSize);
        QueryWrapper<AdminEntity> wrapper = new QueryWrapper<>();
        rowPage = mapper.selectPage(rowPage, wrapper);
        return Result.success(rowPage);
    }

    @Data
    static class Admin {
        private String account;
        private String password;
        private String avatar;
        private String name;
    }

    @JwtToken
    @Operation(summary = "新增")
    @PostMapping("/adminAppend")
    public Result<?> adminAppend(@RequestBody Admin admin) {
        QueryWrapper<AdminEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("name", admin.getName());
        if (service.getOne(wrapper) != null) {
            return Result.failure("名称已存在");
        }
        wrapper.eq("account", admin.getAccount());
        if (service.getOne(wrapper) != null) {
            return Result.failure("账号已存在");
        }
        AdminEntity entity = new AdminEntity();
        BeanUtils.copyProperties(admin, entity);
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(entity.getPassword().getBytes(StandardCharsets.UTF_8));
        entity.setPassword(md5DigestAsHex);
        return Result.success(service.save(entity));
    }

    @JwtToken
    @Operation(summary = "删除")
    @PostMapping("/adminDelete")
    public Result<?> adminDelete(@RequestParam Integer id) {
        return Result.success(service.removeById(id));
    }

    @JwtToken
    @Operation(summary = "编辑")
    @PostMapping("/adminEditor")
    public Result<?> adminEditor(@RequestBody AdminEntity adminEntity) {
        QueryWrapper<AdminEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("id", adminEntity.getId());
        //修改过名称
        if (!Objects.equals(service.getOne(wrapper).getName(), adminEntity.getName())) {
            QueryWrapper<AdminEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name", adminEntity.getName());
            if (service.count(queryWrapper) != 0) {
                return Result.failure("名称已存在");
            }
        }
        return Result.success(service.updateById(adminEntity));
    }

    @JwtToken
    @Operation(summary = "搜索")
    @PostMapping("/adminSearch")
    public Result<?> adminSearch(@RequestParam String name) {
        QueryWrapper<AdminEntity> wrapper = new QueryWrapper<>();
        wrapper.like("name", name);
        return Result.success(mapper.selectList(wrapper));
    }

    @Operation(summary = "登录")
    @PostMapping("/adminLogin")
    public Result<?> adminLogin(@RequestParam String account, @RequestParam String password, @RequestParam String code, HttpSession session) {
        //if (ObjectUtils.isEmpty(session.getAttribute("code"))) {
        //    return Result.failure("验证码生成错误");
        //}
        //if (!session.getAttribute("code").equals(code)) {
        //    return Result.failure("验证码错误");
        //}
        QueryWrapper<AdminEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("account", account);
        AdminEntity admin = service.getOne(wrapper);
        if (admin == null) {
            return Result.failure("账号不存在，登陆失败");
        }
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        if (!password.equals(admin.getPassword())) {
            return Result.failure("密码错误，登陆失败");
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("id", admin.getId().toString());
        map.put("account", admin.getAccount());
        map.put("name", admin.getName());
        String token = JWTUtils.generateToken(map);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("token", token);
        hashMap.put("admin", admin);
        return Result.success("登录成功", hashMap);
    }

    @JwtToken
    @Operation(summary = "修改密码")
    @PostMapping("/adminChangePass")
    public Result<?> adminChangePass(@RequestParam String id, @RequestParam String oldPwd, @RequestParam String newPwd) {
        AdminEntity admin = service.getById(id);
        oldPwd = DigestUtils.md5DigestAsHex(oldPwd.getBytes(StandardCharsets.UTF_8));
        if (!oldPwd.equals(admin.getPassword())) {
            return Result.failure("原密码错误");
        }
        newPwd = DigestUtils.md5DigestAsHex(newPwd.getBytes(StandardCharsets.UTF_8));
        admin.setPassword(newPwd);
        if (service.updateById(admin)) {
            return Result.success("成功,请重新登陆");
        }
        return Result.success("系统超时，失败");
    }


}
